<?php

/**
 *    合作伙伴控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class OrderApp extends BackendApp
{
    /**
     *    管理
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function index()
    {
        $isexport = isset($_GET['isexport'])?true:false;
        $order_status = isset($_GET['status'])?intval($_GET['status']):0;
        $search_options = array(
            'seller_name'   => Lang::get('store_name'),
            'buyer_name'   => Lang::get('buyer_name'),
            'order_sn'   => Lang::get('order_sn'),
            'out_trade_sn'   => Lang::get('out_trade_sn'),
        );
        /* 默认搜索的字段是店铺名 */
        $field = 'seller_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];
        $conditions = $this->_get_query_conditions(array(array(
                'field' => $field,       //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name'  => 'search_name',
            ),array(
                'field' => 'status',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
            'field' => 'pay_time',
            'name'  => 'pay_time_from',
            'equal' => '>=',
            'handler'=> 'gmstr2time',
            ),array(
                'field' => 'pay_time',
                'name'  => 'pay_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_from',
                'equal' => '>=',
                'type'  => 'numeric',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_to',
                'equal' => '<=',
                'type'  => 'numeric',
            ),
        ));
        $model_order =& m('order');
        $page   =   $this->_get_page(10);    //获取分页信息
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
             $sort  = 'add_time';
             $order = 'desc';
            }
        }
        else
        {
            $sort  = 'add_time';
            $order = 'desc';
        }
        $page['limit'] = $isexport ? '' : $page['limit'];
        $orders = $model_order->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit'         => $page['limit'],  //获取当前页的数据
            'order'         => "$sort $order",
            'count'         => true           //允许统计
        )); //找出所有商城的合作伙伴
        require(ROOT_PATH . '/includes/cfg_status.php');//配置文件
        foreach ($orders as $key=>$val)
        {
        	$orders[$key]['payment_name'] = $cfg_pay_type[$val['payment_code']];
            $returns = $this->_get_returns($val['order_id']);
            if($returns)
            {
                $orders[$key]['returns'] = 1;
            }
        }

        //导出数据
        if($isexport && $orders)
        {
            $model_ordergoods =& m('ordergoods');
            $order_ids = $model_order->getCol("SELECT order_id FROM {$model_order->table} WHERE 1=1 ". $conditions);
            $sql = "select o.order_id,o.order_sn,o.pay_time,o.seller_name,o.status,o.add_time,o.order_amount,o.payment_code,o.ship_time,o.invoice_no,oe.shipping_name,oe.consignee,oe.phone_mob,oe.phone_tel,oe.shipping_fee,gs.sku,og.rec_id,og.goods_id,og.goods_name,og.price,og.quantity,og.price*og.quantity as total_goods_amount
                    from " .DB_PREFIX."order_goods og
                    left join " .DB_PREFIX."order o on og.order_id=o.order_id
                    left join " .DB_PREFIX."order_extm  oe on og.order_id=oe.order_id
                    left join " .DB_PREFIX."goods_spec gs on og.spec_id=gs.spec_id
                    where og.order_id " . db_create_in($order_ids) ." order by o.pay_time desc";
            $export_orders = $model_ordergoods->getAll($sql);
            if(count($export_orders) > 1000){
                echo "<script>alert('数据量太大，请筛选分批导出');history.back();</script>";
            }
            else
            {
                foreach($export_orders as $key=>$val)
                {
                    $data[$val['order_id']][$val['rec_id']] = $val;
                    $data[$val['order_id']][$val['rec_id']]['returns'] = $orders[$val['order_id']]['returns'];
                    $data[$val['order_id']][$val['rec_id']]['payment_name'] =  $cfg_pay_type[$data[$val['order_id']][$val['rec_id']]['payment_code']];
                }
                
                $this->_out_put_excel($data,$order_status);
            }
        }

        $page['item_count'] = $model_order->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->assign('order_status_list', array(
            ORDER_PENDING => Lang::get('order_pending'),
            ORDER_SUBMITTED => Lang::get('order_submitted'),
            ORDER_ACCEPTED => Lang::get('order_accepted'),
            ORDER_SHIPPED => Lang::get('order_shipped'),
            ORDER_FINISHED => Lang::get('order_finished'),
            ORDER_CANCELED => Lang::get('order_canceled'),
            ORDER_CLOSED => Lang::get('order_closed'),
        ));
        $this->assign('search_options', $search_options);
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->assign('orders', $orders);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('order.index.html');
    }

    /**
     *    查看
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function view()
    {
        $order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$order_id)
        {
            $this->show_warning('no_such_order');

            return;
        }

        require(ROOT_PATH . '/includes/cfg_status.php');//配置文件
        /* 获取订单信息 */
        $model_order =& m('order');
        $order_info = $model_order->get(array(
            'conditions'    => $order_id,
            'join'          => 'has_orderextm',
            'include'       => array(
                'has_ordergoods',   //取出订单商品
            ),
        ));

        $order_info['payment_name'] = $cfg_pay_type[$order_info['payment_code']];

        /* 获取订单支付金额信息 */
        $model_order_money =& m('ordermoney');
        $order_money_info = $model_order_money->get(array(
            'conditions'    => 'order_id ='. $order_id,
        ));

        if (!$order_info)
        {
            $this->show_warning('no_such_order');
            return;
        }
        $order_type =& ot($order_info['extension']);
        $order_detail = $order_type->get_order_detail($order_id, $order_info);
        $order_info['group_id'] = 0;
         $returns = $this->_get_returns($order_id);
        if($returns)
        {
            $order_info['returns_list'] = $returns;
        }
        if ($order_info['extension'] == 'groupbuy')
        {
            $groupbuy_mod =& m('groupbuy');
            $groupbuy = $groupbuy_mod->get(array(
                'fields' => 'groupbuy.group_id',
                'join' => 'be_join',
                'conditions' => "order_id = {$order_info['order_id']} ",
                )
            );
            $order_info['group_id'] = $groupbuy['group_id'];
        }
        if($_GET['print'] == 1)
        {
            $returns_arr = $this->_get_returns($order_id,true);
            if($returns_arr)
            {
                foreach($returns_arr as $key => $val)
                {
                    $returns_data[$val['rec_id']] = $val;
                }
            }

        }
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            if (substr($goods['goods_image'], 0, 7) != 'http://')
            {
                $order_detail['data']['goods_list'][$key]['goods_image'] = SITE_URL . '/' . $goods['goods_image'];               
            }
            $order_detail['data']['goods_list'][$key]['goods_amount'] = number_format($goods['price']*$goods['quantity'],2);
            if(isset($returns_data[$goods['rec_id']]))
            {
                $order_detail['data']['goods_list'][$key]['returns_quantity'] = $returns_data[$goods['rec_id']]['quantity'];
                $order_detail['data']['goods_list'][$key]['returns_amount'] = $returns_data[$goods['rec_id']]['returns_amount'];
                $returns_amount_total += $returns_data[$goods['rec_id']]['returns_amount'];
            }
        }
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.ui/i18n/' . i18n_code() . '.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'mlselection.js',
                    'attr' => ''
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));
        $this->assign('order', $order_info);
        $this->assign('order_money', $order_money_info);
        $this->assign($order_detail['data']);
        if($_GET['print'] == 1)
        {
            $this->assign('returns_amount_total', number_format($returns_amount_total, 2));
            $this->display('order.print.html');
        }
        else
        {
            $this->display('order.view.html');
        }
        
    }

    /**
     *    待发货的订单发货
     *
     *    @author    Garbin
     *    @return    void
     */
    function shipped()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(array(ORDER_ACCEPTED, ORDER_SHIPPED));
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        $model_order = & m('order');
        $model_orderextm = & m("orderextm");
        $model_returns = & m('returns');
        $order_returns = $model_returns->order_returns($order_id);
        include(ROOT_PATH . '/includes/cfg_status.php');

        if (!IS_POST)
        {
            /* 显示发货表单 */
            header('Content-Type:text/html;charset=' . CHARSET);
            $orderextm = $model_orderextm->get(array(
                'conditions' => "order_id = '{$order_id}'",
                'fields' => 'shipping_name'
            ));
            $shipping_names = $this->_get_shipping_names();
            $this->assign('other', false);
            if ($orderextm && !in_array($orderextm['shipping_name'], $shipping_names))
                $this->assign('other', true);
            $this->assign('order', $order_info);
            $this->assign('order_returns', $order_returns);
            $this->assign('cfg_shipping_kuaidi', $cfg_shipping_kuaidi);
            $this->assign('orderextm', $orderextm);
            $this->display('order.shipped.html');
        }
        else
        {
            $shipping_name = empty($_POST['their']) ? $_POST['express'] : '自提';
            $invoice_no = empty($_POST['their']) ? html_script($_POST['invoice_no']) : '自提';
            $shipping_code = isset($cfg_shipping_kuaidi[$shipping_name]) ? $cfg_shipping_kuaidi[$shipping_name] : '';

            if (!$invoice_no)
            {
                $this->pop_warning('请输入物流单号');
                return;
            }
            if (!$shipping_name)
            {
                $this->pop_warning('请选择物流公司');
                return;
            }

            $edit_data = array('status' => ORDER_SHIPPED, 'invoice_no' => $invoice_no);
            $is_edit = true;
            if (empty($order_info['invoice_no']))
            {
                /* 不是修改发货单号 */
                $edit_data['ship_time'] = gmtime();
                $is_edit = false;
            }
            $model_order->edit(intval($order_id), $edit_data);
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            $model_orderextm->edit(intval($order_id), array('shipping_name' => html_script(trim($shipping_name)),'shipping_code' => $shipping_code));
            if ($model_orderextm->has_error())
            {
                $this->pop_warning($model_orderextm->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_SHIPPED),
                'remark' => $_POST['remark'],
                'log_time' => gmtime(),
            ));




            $new_data = array(
                'status' => Lang::get('order_shipped'),
                'actions' => array(
                    'cancel',
                    'edit_invoice_no'
                ), //可以取消可以发货
            );
            if ($order_info['payment_code'] == 'cod')
            {
                $new_data['actions'][] = 'finish';
            }

            //关闭退货退款申请
            $this->_close_returns($order_id);

            if($shipping_name != '自提')
            {
                /* 发送给买家订单已发货通知 */
                $model_usersafety = & m('usersafety');
                $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
                $order_info['invoice_no'] = $edit_data['invoice_no'];
                if($buyer_info['binding_email'])
                {
                    $mail = get_mail('tobuyer_shipped_notify', array('order' => $order_info));
                    $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
                }

                //发送手机短信
                $model_order_extm = & m('orderextm');
                $mobile = $model_order_extm->get_fields_name($order_id, 'phone_mob');
                if (!empty($mobile))
                {
                    $msg = '尊敬的会员，您的订单' . $order_info['order_sn'] . '已发货，物流公司：' . $shipping_name . '，物流单号：' . $edit_data['invoice_no'] . '，货物正飞奔到您身边，请注意查收。';
                    include(ROOT_PATH . '/includes/sendsms/ueswt.php');
                    $gckj = new ueswt();
                    $gckj->send_sms($msg, $mobile);
                }
            }

            $backUrl = isset($_GET['ajax']) ? "" : "index.php?app=order&act=view&id={$order_id}";
            $this->pop_warning('ok', '', $backUrl);
        }
    }
    
    function add_track()
    {
        $order_id = isset($_GET['id']) ? $_GET['id'] : 0;
        $track_type = 1;
        if(!$order_id){
            $this->show_warning('no_such_order');
            return;
        }
        
        $track_mod = m("infotrack");
        
        if(!IS_POST){
            $tracks = $track_mod->find("track_id='{$order_id}' AND track_type='{$track_type}'");
            $this->assign("tracks", $tracks);
            $this->assign("title_name", '订单跟进');
            $this->import_resource('jquery.plugins/jquery.validate.js');
            $this->display("order.track.html");
        }else{
            $track_user = html_script(trim($_POST['track_user']));
            $track_info = html_script(trim($_POST['track_info']));
            
            if(!$track_info || !$track_user){
                $this->show_warning('表单信息不全');
                return;
            }
            
            $track_mod->add(array(
                    'track_id' => $order_id,
                    'track_type' => $track_type,
                    'track_user' => $track_user,
                    'track_info' => $track_info,
                    'track_time' => time(),
            ));
            
            $this->show_message('添加订单跟进信息成功！');
            return;
        }
    }

    /**
     *    获取有效的订单信息
     *
     *    @author    Garbin
     *    @param     array $status
     *    @param     string $ext
     *    @return    array
     */
    function _get_valid_order_info($status, $ext = '')
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {
            return array();
        }
        if (!is_array($status))
        {
            $status = array($status);
        }

        if ($ext)
        {
            $ext = ' AND ' . $ext;
        }

        $model_order = & m('order');
        /* 只有已发货的货到付款订单可以收货 */
        $order_info = $model_order->get(array(
            'conditions' => "order_id={$order_id} AND status " . db_create_in($status) . $ext,
        ));
        if (empty($order_info))
        {
            return array();
        }

        return array($order_id, $order_info);
    }

    private function _get_shipping_names()
    {
        return array(
            '顺丰快递', 'EMS快递', '圆通快递', '中通快递', '申通快递', '韵达快递', '中国邮政', '天天快递'
        );
    }

    private function _close_returns($order_id)
    {
        $model_order = & m('order');

        $order_info = $model_order->get(array(
            'fields' => "this.invoice_no,orderextm.shipping_name",
            'conditions' => "order_alias.order_id={$order_id}",
            'join' => 'has_orderextm',
        ));
        if (!empty($order_info))
        {
            $model_returns = & m('returns');
            $model_returns->close_returns($order_id, 2, $order_info['shipping_name'], $order_info['invoice_no']);
        }
    }

    function _get_returns($order_id, $is_agree = false)
    {
        $conditions =" AND returns.order_id = {$order_id}";
        if($is_agree)
        {
            $conditions .=" AND returns.status IN(7,8)";
        }
        else
        {
            $conditions .=" AND returns.status IN(1,3,4,5,6,7,8)";
        }
        $returns_mod =& m('returns');
        $returns = $returns_mod->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'fields'         => "this.returns_id,this.returns_sn,this.quantity,this.returns_amount,this.goods_amount,this.shipping_fee,this.returns_reason,order_goods.rec_id,order_goods.goods_id,order_goods.goods_image,order_goods.goods_name,order_goods.specification",
            'join' => 'belongs_to_ordergoods',
            'order'         => "add_time DESC",
        ));
        return $returns;
    }

    function pop_warning ($msg, $dialog_id = '',$url = '')
    {
        if($msg == 'ok')
        {
            if(empty($dialog_id))
            {
                $dialog_id = APP . '_' . ACT;
            }
            if (!empty($url))
            {
                echo "<script type='text/javascript'>window.location.href='".$url."';</script>";
            }

            echo "<script type='text/javascript'>window.parent.js_success('" . $dialog_id ."');</script>";
        }
        else
        {
            header("Content-Type:text/html;charset=".CHARSET);
            $msg = is_array($msg) ? $msg : array(array('msg' => $msg));
            $errors = '';
            foreach ($msg as $k => $v)
            {
                $error = $v[obj] ? Lang::get($v[msg]) . " [" . Lang::get($v[obj]) . "]" : Lang::get($v[msg]);
                $errors .= $errors ? "<br />" . $error : $error;
            }
            echo "<script type='text/javascript'>window.parent.js_fail('" . $errors . "');</script>";
        }
    }

    function _out_put_excel($data,$order_status=0)
    {

        $index = 1;
        foreach ($data as $order)
        {
            $count = count($order);
            sort($order);
            foreach ($order as $key => $goods)
            {
                $rs[$index-1] = $goods ;
                $rs[$index-1]['status'] = $rs[$index-1]['returns'] == 1 ? order_status($rs[$index-1]['status']).'(有退款)' : order_status($rs[$index-1]['status']);
                $rs[$index-1]['phone'] = !empty($rs[$index-1]['phone_mob'])?$rs[$index-1]['phone_mob']:$rs[$index-1]['phone_tel'];
                $rs[$index-1]['add_time'] = date('Y-m-d H:i:s',$rs[$index-1]['add_time']);
                $rs[$index-1]['ship_time'] = date('Y-m-d H:i:s',$rs[$index-1]['ship_time']);
                $rs[$index-1]['pay_time'] = !empty($rs[$index-1]['pay_time']) ? date('Y-m-d H:i:s',$rs[$index-1]['pay_time']) : '';
                if($key == 0 && $count>1)
                {
                    $rs[$index-1]['rowspan'] = $count-1;
                }

                $index++;
            }
        }
        $heads = $this->_get_excel_heads($order_status);
        require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
        createExcel('订单信息', $heads, $rs, 1);
        exit;
    }

    function _get_excel_heads($order_status=0)
    {
        $arr = array();
        if($order_status >=30)
        {
            $arr =  array(
                'order_sn' => array('name' => "订单号", 'rowspan' => true),
                'consignee' => array('name' => "收货人姓名", 'rowspan' => true),
                'phone' => array('name' => "联系电话", 'rowspan' => true),
                'add_time' => array('name' => "下单时间", 'rowspan' => true),
                'pay_time' => array('name' => "支付时间", 'rowspan' => true),
                'payment_name' => array('name' => "支付方式", 'rowspan' => true),
                'status' => array('name' => "订单状态", 'rowspan' => true),
                'ship_time' => array('name' => "发货时间", 'rowspan' => true),
                'shipping_name' => array('name' => "快递公司", 'rowspan' => true),
                'invoice_no' => array('name' => "快递单号", 'rowspan' => true),
                'seller_name' => array('name' => "店铺名", 'rowspan' => true),
                'goods_name' => array('name' => "商品名称"),
                'quantity' => array('name' => "数量"),
                'price' => array('name' => "单价"),
                'total_goods_amount' => array('name' => "小计"),
                'sku' => array('name' => "货号"),
                'order_amount' => array('name' => "订单总价", 'rowspan' => true),
            );
        }
        else
        {
           $arr =  array(
                'order_sn' => array('name' => "订单号", 'rowspan' => true),
                'consignee' => array('name' => "收货人姓名", 'rowspan' => true),
                'phone' => array('name' => "联系电话", 'rowspan' => true),
                'add_time' => array('name' => "下单时间", 'rowspan' => true),
                'pay_time' => array('name' => "支付时间", 'rowspan' => true),
                'payment_name' => array('name' => "支付方式", 'rowspan' => true),
                'status' => array('name' => "订单状态", 'rowspan' => true),
                'seller_name' => array('name' => "店铺名", 'rowspan' => true),
                'goods_name' => array('name' => "商品名称"),
                'quantity' => array('name' => "数量"),
                'price' => array('name' => "单价"),
                'total_goods_amount' => array('name' => "小计"),
                'sku' => array('name' => "货号"),
                'order_amount' => array('name' => "订单总价", 'rowspan' => true),
            );
        }

        return  $arr;
    }
}
?>
